<?php
/**
 * Created by paperphp
 * User: 22071
 * Date: 2019/6/25
 * Email: <zhendongdong@foxmail.com>
 */


namespace paper;


use paper\server\Server;

class Url implements Server
{
    private $path = '';
    private $params = '';
    private $app = null;

    /**
     * 实例化
     * Url constructor.
     * @param App $app
     */
    public function __construct(App $app)
    {
        $this->app = $app;
    }


    /**显示包含域名在内的完成地址
     * @param $domain
     * @return string
     */
    public function full($domain = '')
    {
        //返回带当前访问域名的完整地址
        $domain = $domain ?: $this->app->request->domain();
        return '//' . $domain . $this->build();
    }

    /**
     * 显示不带参数的当前地址（自动隐藏非必要显示的部分）
     * @return string
     */
    public function current()
    {
        return $this->app->request->path();
    }

    /**
     * 设置url
     * @param string $path
     * @param string $params
     * @return Url|string
     */
    public function path($path = '', $params = '')
    {
        $this->path   = $path;
        $this->params = '';
        if ($path && false !== strpos($path, '?')) {
            $queryString  = explode("?", $path);
            $this->path   = $queryString[0];
            $this->params = $queryString[1];
        } elseif ($params) {
            $this->params = http_build_query($params);
        }
        return $this;
    }


    /**
     * 构建URL
     * @return string
     */
    public function build()
    {

        if (!$this->path) {
            $this->path = $this->current();
        } else {
            if (strpos($this->path, "/") !== 0) {
                $this->path = '/' . $this->app->request->module(false)
                    . '/' . $this->app->request->controller(false)
                    . '/' . $this->path;
            }
        }

        //根据配置判断是否需要显示入口文件

        $suffix = $this->app->config->app("url_suffix");
        $model  = $this->app->config->app("url_mode");

        $suffix    = $suffix && $this->path != '/' ? '.' . $suffix : '';
        $enterFile = $model == 1 ? '' : $this->getEnterFile();
        //        echo '[' . $enterFile . $this->path . $suffix . ($this->params ? '?' . $this->params : "") . ']';
        return $enterFile . $this->path . $suffix . ($this->params ? '?' . $this->params : "");
    }

    /**
     * 获取入口文件
     * @return mixed|string
     */
    public function getEnterFile()
    {
        return $this->app->request->server("SCRIPT_NAME");
    }

    public function __toString(): string
    {
        return $this->build();
    }

    /**
     * 系统服务注册
     * @param App $app
     */
    public static function _make(App $app)
    {
        $app->bind(self::class);
    }
}